package com.tsugun.mediaplayer.presenter.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory

import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL

/**
 * 网络请求工具类
 * Created by shize on 2017/8/9.
 */

object HttpHelper {
    val START_URL = "http://music.163.com/api/search/artist/pic?name="
    val END_URL = "&imageView=1&thumbnail=149z149&type=webp&quality=80"

    /**
     * 解析json数据，获取图片地址
     */
    fun getImageURL(artist: String): URL? {
        var url: URL? = null
        try {
            url = URL(START_URL + artist + END_URL)
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        }

        return url
    }

    /**
     * 下载图片

     * @param url 图片地址
     * *
     * @return 图片bitmap
     */
    fun downloadBitmap(url: URL): Bitmap? {
        var bitmap: Bitmap? = null
        try {
            // 使用HttpURLConnection打开链接
            val connection = url.openConnection() as HttpURLConnection
            connection.doInput = true
            connection.connect()
            // 将得到的数据转化为InputStream
            val `is` = connection.inputStream
            // 再将InputStream转换为Bitmap
            bitmap = BitmapFactory.decodeStream(`is`)
            CloseHelper.closeQuietly(`is`)
        } catch (e: IOException) {
            e.printStackTrace()
        }

        return bitmap
    }
}
